<template>
  <div class="noselect">
    <div class="play-wrapper" @mousedown="inVideo()" @mouseup="isInVideo()" @mousemove.self="mousemove()">
      <div class="top-bar" @mouseup="isinVideo=false" @mouseenter="cancelTimer()" @mouseleave="mousemove()">
        <div class="top-bar-right" @click="close()">
        </div>
      </div>
      <div class="video-player">
        <video id="video" class="video" 
          :src="getUrl(this.url)" @mousemove.self="mousemove()"
          @timeupdate="timeupdate" @canplay="startPlay">
        </video>
      </div>
      <div class="play-bar" @mouseup="isinVideo=false" @mouseenter="cancelTimer()" @mouseleave="mousemove()">
        <div class="progress" @mousedown="progressMousedown">
          <div class="cur-progress" :style="{width: curLength+'%'}"></div>
          <!--拖动的点点-->
          <div class="idot" :style="{left: curLength+'%'}"></div>
        </div>
        <div id="playbtn" @mousedown="inVideo()" @mouseup="isInVideo()">
          <i id="playorpause" class="iconfont icon-playbtn"></i>
        </div>
        <div class="video-time">
          <span>{{curTime}}</span>/
          <span>{{duration}}</span>
        </div>
        <div class="sent-barrage">
          <el-button type="primary" style="margin-right:5px" :style="{color:isBarrage?'white':'#666'}" size="small" @click="isBarrageOn()" circle>弹</el-button>
          <el-input v-model="inputBarrage" placeholder="可发送弹幕" size="small"></el-input>
          <el-button type="primary" size="small" @click="sentBarrage()">发送</el-button>
        </div>
        <div class="play-bar-right">
          <div id="praisebtn" @click="praiseOrcollect(2)">
            <i id="praise" class="iconfont icon-praise01"></i>
          </div>
          <div id="collectbtn" @click="praiseOrcollect(0)">
            <i id="collect" class="iconfont icon-collect"></i>
          </div>
          <div id="beisu">
            <i class="beisu">倍速</i>
            <div class="speed">
              <p class="speedx2" @click="speed(2)">x2.0</p>
              <p class="speedx1.5" @click="speed(1.5)">x1.5</p>
              <p class="speedx1" @click="speed(1)">x1.0</p>
              <p class="speedx0.5" @click="speed(0.5)">x0.5</p>
            </div>
          </div>
          <div id="volume">
            <i id="icon-volume" class="iconfont" 
            :class="{'icon-volume-x':volume==0,
            'icon-volume-':volume>0&&volume<=40,
            'icon-volume-1':volume>40&&volume<=100}" 
            @click.self="mute()"></i>
            <div class="volume-silder-wrapper">
              <el-slider
                class="volume-silder"
                :show-tooltip="false"
                @change="beforemute()"
                vertical
                v-model="volume">
              </el-slider>
            </div>
          </div>
          <div id="quanping" @click="quanping()">
            <i class="iconfont icon-quanping"></i>
          </div>
        </div>
      </div>
      <div v-show="isBarrage" class="barrageContent">
        <span class="barrage" v-for="(item,index) in barrage" :key="index" :style="{top:(index-1)%8*30+'px'}">{{item}}</span>
      </div>
    </div>
  </div>
</template>

<script>
import {addNumber,getPraiseById,getCollectionById,getBarrageById,addBarrage} from '../api/index'
import {mixin} from '../mixins/index'
import {mapGetters} from 'vuex'
export default {
  name:'video-play',
  props:['url','videoId'],
  mixins:[mixin],
  data(){
    return {
      isinVideo:false,   //开始暂停视频按下位置是否都在视频内
      timer:{},          //鼠标移入计时器
      oriBarrage:[],       //原弹幕
      waitBarrage:[],      //待发送弹幕
      barrage:[],          //已发送弹幕
      inputBarrage:'',   //待发送弹幕
      isPlay:false,      //是否正在播放
      isPraise:false,    //是否已点赞
      isCollect:false,   //是否已收藏
      volume:50,         //音量
      volume2:50,        //静音前的音量
      duration:'00:00',  //总时长
      curTime:'00:00',   //当前时长
      curLength: 0,      //进度条的位置
      isMove:false,      //是否正在拖动进度条
    }
  },
  computed:{
    ...mapGetters([
      'loginIn',
      'userId',
      'collection',
      'praise',
      'isBarrage'
    ]),
  },
  watch:{
    isPraise(){
      if(this.isPraise){
        document.getElementById('praise').classList.add('good')
      }else{
        document.getElementById('praise').classList.remove('good')
      }
    },
    isCollect(){
      if(this.isCollect){
        document.getElementById('collect').classList.add('collect')
      }else{
        document.getElementById('collect').classList.remove('collect')
      }
    },
    //监控isPlay改变播放暂停按钮和视频暂停
    isPlay(){
      var video = document.getElementById('video')
      var playbtn = document.getElementById('playorpause')
      if (!this.isPlay) {
        playbtn.classList.replace('icon-pause','icon-playbtn')
        video.pause()
        //弹幕暂停
        let barrage = document.getElementsByClassName('barrage')
        for (let i = 0; i < barrage.length; i++) {
          barrage[i].style.animationPlayState = 'paused'
        }
      }else{
        playbtn.classList.replace('icon-playbtn','icon-pause')
        video.play()
        //弹幕开始
        let barrage = document.getElementsByClassName('barrage')
        for (let i = 0; i < barrage.length; i++) {
          barrage[i].style.animationPlayState = 'running'
        }
      }
    },
    volume(){
      var video = document.getElementById('video')
      video.volume = this.volume/100
    },
    url(){
      this.curLength = 0
    },
  },
  created(){
    setTimeout(() => {
      this.getBarrageById()
    }, 500);

    //全屏
    document.addEventListener("fullscreenchange", function (e) {
      if (document.fullscreenElement) {
        document.getElementsByClassName('video-player')[0].classList.add('video-player-full')
      } else {
        document.getElementsByClassName('video-player')[0].classList.remove('video-player-full')
        document.getElementsByClassName('top-bar')[0].classList.add('top-bar2')
        document.getElementsByClassName('play-bar')[0].classList.add('play-bar2')
      }
    })
    
    //拖拽中
    document.addEventListener('mousemove',(e)=>{
      if (!this.duration) { //若视频长度为0(视频未成功加载)无法拖动
        return false
      }
      if(this.isMove){  
        this.curLength = ((e.clientX - document.getElementsByClassName('progress')[0].getBoundingClientRect().left)/document.getElementsByClassName('progress')[0].getBoundingClientRect().width)*100
        if(this.curLength >=100){
          this.curLength = 100
        }
        if(this.curLength <=0){
          this.curLength = 0
        }
        //当前显示时间
        this.curTime = this.formatTime(this.curLength * document.getElementById('video').duration/100)
      }
    })
    //拖拽结束
    document.addEventListener('mouseup',() =>{
      if (this.isMove) {
        document.getElementById('video').currentTime = this.curLength*document.getElementById('video').duration/100
        this.isMove = false
        this.refreshBarrage()
      }
    })
  },
  mounted(){
    //检查是否已经点赞
    setTimeout(() => {
      for(let i in this.praise){
        if(this.praise[i] == this.videoId){
          this.isPraise = true
        }
      }
      for(let i in this.collection){
        if(this.collection[i] == this.videoId){
          this.isCollect = true
        }
      }
    }, 200);
    //播放条不消失
    document.getElementsByClassName('play-bar')[0].classList.add('play-bar2')
  },
  methods:{
    //点赞或收藏视频
    praiseOrcollect(type){
      var _this = this
      if (!this.userId) {
        this.notify('请先登录','warning')
        return
      }
    
      let formData = new FormData()
      formData.append('id',this.userId)
      formData.append('value',this.videoId)
      formData.append('type',type) //0收藏  1历史  2点赞视频  3点赞评论
      addNumber(formData)

      if (type == 0) {
        this.isCollect = !this.isCollect
        setTimeout(() => {
          getCollectionById(this.userId)
            .then(res =>{
              var collection = res.videoIds.split('-')
              _this.$store.commit('setCollection',collection)
            })
        }, 100);
      }else if(type == 2){
        this.isPraise = !this.isPraise
        setTimeout(() => {
          getPraiseById(this.userId)
            .then(res =>{
              var praise = res.videoIds.split('-')
              _this.$store.commit('setPraise',praise)
            })
        }, 100);
      }
      
    },
    //开始播放视频
    startPlay(){
      this.duration = this.formatTime(document.getElementById('video').duration)
    },
    //当视频时间更新执行
    timeupdate(){
      if(!this.isMove){
        //显示时间
        this.curTime = this.formatTime(document.getElementById('video').currentTime)
        this.curLength = (document.getElementById('video').currentTime/document.getElementById('video').duration)*100
      }

      //根据时间出现弹幕
      var curTime = document.getElementById('video').currentTime
      if (curTime != 0) {
        while(this.waitBarrage[0] != undefined && curTime > this.waitBarrage[0].time){
          this.barrage.push(this.waitBarrage[0].content)
          this.waitBarrage.shift()
        }
      }
    },
    //鼠标移动→视频信息出现
    mousemove(){
      if(document.fullscreenElement){
        var ele = document.getElementsByClassName('top-bar')[0]
        var ele2 = document.getElementsByClassName('play-bar')[0]
        ele.classList.add('top-bar2')
        ele2.classList.add('play-bar2')
        clearTimeout(this.timer)
        this.timer = setTimeout(() =>{
          ele.classList.remove('top-bar2')
          ele2.classList.remove('play-bar2')
        },1000)
      }
    },
    //取消timer
    cancelTimer(){
      clearTimeout(this.timer)
    },
    //全屏
    quanping(){
      var player = document.getElementsByClassName('play-wrapper')[0]
      if(document.fullscreenElement){
        if(document.exitFullscreen){
          document.exitFullscreen();
        }else if(document.webkitCancelFullScreen){
          document.webkitCancelFullScreen();  //Chrome,safari
        }else if(document.mozCancelFullScreen){
          document.mozCancelFullScreen(); //firefox
        }else if(document.msExitFullScreen){
          document.msExitFullScreen();   //ie
        }
      }else{
        if(player.requestFullscreen){
          player.requestFullscreen();
        }else if(player.webkitRequestFullscreen){
          player.webkitMatchesSelector();
        }else if(player.mozRequestFullscreen){
          player.mozRequestFullscreen();
        }else if(player.msRequestFullscreen){
          player.msRequestFullscreen();
        }
      }
    },
    //按下时在视频内(播放暂停功能)
    inVideo(){
      this.isinVideo = true
    },
    //松开时在视频内(播放暂停功能)
    isInVideo(){
      if(this.isinVideo){
        this.isPlay = !this.isPlay
      }
      this.isinVideo = false
    }, 
    //改变视频速度
    speed(sudu){
      document.getElementById('video').playbackRate = sudu
    },
    //静音前的音量
    beforemute(){
      if(this.volume != 0){
        this.volume2 = this.volume
      }
    },
    //点击音量静音
    mute(){
      if(this.volume != 0){
        this.volume = 0
      }else{
        this.volume = this.volume2
      }
    },
    //拖拽开始
    progressMousedown (e) {
      //((当前鼠标相对页面的x坐标-总进度条的左边界相对于页面的距离)/总进度条总宽度)/100
      this.curLength = ((e.clientX - document.getElementsByClassName('progress')[0].getBoundingClientRect().left)/document.getElementsByClassName('progress')[0].getBoundingClientRect().width)*100
      this.isMove = true   
    },
    //发送弹幕
    sentBarrage(){
      if (this.loginIn) {
        let params = new URLSearchParams()
        let time = document.getElementById('video').currentTime.toFixed(3)
        let newBarrage = this.inputBarrage;
        params.append('id',this.videoId)
        params.append('consumerId',this.userId+":")
        params.append('time',time)
        params.append('content',newBarrage)
        addBarrage(params)
          .then(() =>{
            this.waitBarrage.unshift({"time":time,"consumerId":this.userId,"content":newBarrage})
            let i = 0;
            while(this.oriBarrage[i].time < time){
              i++
            }
            this.oriBarrage.splice(i,0,{"time":time,"consumerId":this.userId,"content":newBarrage})
          })
        this.inputBarrage = ''
      }else{
        this.notify('请先登录','warning')
      }
    },
    //获取弹幕
    getBarrageById(){
      getBarrageById(this.videoId)
        .then(res =>{
          this.oriBarrage = res.slice(0)
          this.refreshBarrage()
        })
    },
    //刷新弹幕(删除当前时间之前的弹幕)
    refreshBarrage(){
      this.waitBarrage = this.oriBarrage.slice(0)
      var time = document.getElementById('video').currentTime
      while (this.waitBarrage[0] != undefined && this.waitBarrage[0].time < time) {
        this.waitBarrage.shift()
      }
    },
    //是否开启弹幕
    isBarrageOn(){
      if (this.isBarrage) {
        this.$store.commit('setIsBarrage',false)
        this.barrage = []
      }else{
        this.refreshBarrage()
        this.$store.commit('setIsBarrage',true)
      }
    }
  }
}
</script>

<style scoped>
@import '../assets/css/videoPlay.css';
</style>